import Vue from 'vue'
import Router from 'vue-router'
// import { actionTrack } from '@/assets/js/utils'
import { Dialog, Toast } from 'vant'
import { get } from '@/assets/service/http'
Vue.use(Router)

/**
 * meta中特殊参数说明
 * @param unAuthorization // 不用走网页授权获取openid
 * @param setMenuAndShareInPage // 在路由对应的页面中，设置微信工具菜单的显隐和分享
 * @param showAllMenu // 展示所有微信工具菜单
 * @param showMenuList // 需要展示的微信工具菜单
 * @param forbitShare // 禁止自定义分享
 * @param shareInfo // 分享的配置信息 title、desc、link、imgUrl
 */
const route = new Router({
  mode: 'history',
  base: `${process.env.VUE_APP_BASE_URL}${process.env.VUE_APP_VERSION}/`,
  routes: [
    {
      path: '/',
      redirect: '/home'
    },
    {
      path: '/index',
      name: 'index',
      component: () => import('@/views/index')
    },
    {
      path: '/home',
      name: 'meetingHome',
      component: () => import('@/views/meeting/home'),
      meta: {
        title: '会议主页',
        setMenuAndShareInPage: true
      }
    },
    {
      path: '/apply',
      name: 'meetingApply',
      component: () => import('@/views/meeting/apply'),
      meta: {
        title: '报名',
        showMenuList: [],
        forbitShare: true
      }
    },
    {
      path: '/applyConfirm',
      name: 'meetingApplyConfirm',
      component: () => import('@/views/meeting/applyConfirm'),
      meta: {
        title: '确认报名',
        showMenuList: [],
        forbitShare: true
      }
    },
    {
      path: '/location',
      name: 'meetingLocation',
      component: () => import('@/views/meeting/location'),
      meta: {
        title: '会议地点',
        showMenuList: [],
        forbitShare: true
      }
    },
    {
      path: '/personCenter',
      name: 'meetingPersonCenter',
      component: () => import('@/views/meeting/personCenter'),
      meta: {
        title: '会议中心',
        showMenuList: [],
        forbitShare: true
      }
    },
    {
      path: '/meetingList/:type',
      name: 'meetingList',
      component: () => import('@/views/meeting/list'),
      meta: {
        title: '会议中心',
        showMenuList: [],
        forbitShare: true
      }
    },
    {
      path: '*',
      name: 'notFound',
      component: () => import('@/views/not_found')
    }
  ]
})

// 获取当前应用项目对应的appid
let getAppid = (to) => {
  return new Promise((resolve, reject) => {
    // 暂无接口，模拟已经获取appid 和 projectId
    sessionStorage.setItem('appid', 'wxcb97a1ce67b41347') // 公众号appid 悦米技术服务 项目版
    sessionStorage.setItem('projectId', '1')
    if (sessionStorage.getItem('appid')) {
      resolve('获取公众号appid成功')
    } else {
      // 通过项目Id，获取对应的appid
      if (to.query && to.query.projectId) {
        sessionStorage.setItem('projectId', to.query.projectId)
        // let vue = new Vue()
        // let url = `${vue.SERVICE_PORTAL}/${to.query.projectId}`
        // let param = {}
        // get(url, param).then(res => {
        //   if (res.code === 200 && res.data) {
        //     sessionStorage.setItem('appid', res.data)
        //     resolve('获取公众号appid成功')
        //   } else {
        //     reject(new Error('获取公众号appid失败'))
        //   }
        // })
      } else {
        reject(new Error('获取公众号appid失败'))
      }
    }
  })
}

// 获取当前路径上的openid 和 isRedrect
let checkRouteQuery = (to) => {
  if (to.query && to.query.openid) {
    sessionStorage.setItem('openid', to.query.openid)
  }
  if (to.query && to.query.redirect) {
    sessionStorage.setItem('isRedirect', to.query.redirect)
  }
}

// 获取全局参数————公众号信息
let getWechatMpInfo = () => {
  return new Promise((resolve, reject) => {
    let vue = new Vue()
    let url = `${vue.SERVICE_PORTAL}/${sessionStorage.getItem('appid')}`
    let param = {}
    get(url, param).then(res => {
      if (res.code === 200) {
        if (res.data) {
          localStorage.setItem('wechatInfo', JSON.stringify(res.data))
        } else {
          localStorage.setItem('wechatInfo', JSON.stringify({}))
        }
        resolve('获取公众号信息成功')
      } else {
        reject(new Error('获取公众号信息失败'))
      }
    })
  })
}

// 获取全局参数————粉丝信息
let getFansInfo = () => {
  return new Promise((resolve, reject) => {
    // 如果没有拿到openid, 不调用粉丝接口
    console.log('openid: ', sessionStorage.getItem('openid'))
    console.log('typeof: ', typeof sessionStorage.getItem('openid'))
    if (!sessionStorage.getItem('openid')) {
      localStorage.setItem('isSubscribe', 0)
      localStorage.setItem('fansAvatar', '')
      localStorage.setItem('fansNickName', '')
      localStorage.setItem('userName', '')
      localStorage.setItem('userType', -1)
      localStorage.setItem('userId', '')
      return resolve('获取粉丝信息成功')
    }
    let vue = new Vue()
    let url = `${vue.SERVICE_PORTAL}/${sessionStorage.getItem('appid')}/fans/${sessionStorage.getItem('openid')}`
    let param = {}
    get(url, param).then(rsp => {
      if (rsp.code === 200) {
        if (rsp.data) {
          let baseInfo = rsp.data.baseInfo
          let userInfo = rsp.data.userInfo
          localStorage.setItem('isSubscribe', baseInfo && baseInfo.isSubscribe ? baseInfo.isSubscribe : 0)
          localStorage.setItem('fansAvatar', userInfo && userInfo.avatar ? userInfo.avatar : '')
          localStorage.setItem('fansNickName', userInfo && userInfo.nickName ? userInfo.nickName : '')
          localStorage.setItem('userName', userInfo && userInfo.realName ? userInfo.realName : '')
          localStorage.setItem('userType', userInfo && userInfo.userType ? userInfo.userType : -1)
          localStorage.setItem('userId', userInfo && userInfo.userId ? userInfo.userId : '')
        } else {
          localStorage.setItem('isSubscribe', 0)
          localStorage.setItem('fansAvatar', '')
          localStorage.setItem('fansNickName', '')
          localStorage.setItem('userName', '')
          localStorage.setItem('userType', -1)
          localStorage.setItem('userId', '')
        }
        resolve('获取粉丝信息成功')
      } else {
        reject(new Error('获取粉丝信息失败'))
      }
    })
  })
}

// 通过授权, 获取openid
let checkOpenid = () => {
  return new Promise((resolve, reject) => {
    // 如果已经有openid，直接进行后续操作
    if (sessionStorage.getItem('openid')) {
      resolve()
    // 如果没有openid
    } else {
      // 如果没有openid, 但已经进行过网页授权，则弹出提示
      if (sessionStorage.getItem('isRedirect')) {
        Toast({
          message: '网页授权失败，无法获取openid'
        })
      // 否则进行网页授权
      } else {
        // 通过当前页面url获取重定向地址
        let pagePath = encodeURIComponent(`${location.href}`) // 重定向路由的参数，需要加在 targetUrl中
        let targetUrl = ''
        targetUrl = `${location.origin}${process.env.VUE_APP_SERVICE_API}/wechat/server/response/redirect?target_redirect=${pagePath}`
        let realTargetUrl = encodeURIComponent(targetUrl).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '+')
        // let realTargetUrl = encodeURIComponent(targetUrl)
        let url = '/wechat/server/response/get_oauth2_url'
        let param = {
          targetUrl: realTargetUrl,
          appid: sessionStorage.getItem('appid')
        }
        get(url, param, {}).then(res => {
          if (res.code === 200) {
            let url = res.data.url
            location.href = url
            // vue.console('get_oauth2_url: ', url)
          }
        })
      }
    }
  })
}

// 获取全局参数
let getGlobalData = (next) => {
  // 判断是否获取了全局参数, 直接进行后续操作
  if (sessionStorage.getItem('gotGlobalData')) {
    next()
  // 如果没有, 则先获取全局参数
  } else {
    Promise.all([
      getWechatMpInfo(),
      getFansInfo()
    ]).then(res => {
      sessionStorage.setItem('gotGlobalData', true)
      next()
    }).catch(e => {
      Toast({
        message: e.message || '获取全局参数失败'
      })
    })
  }
}

route.beforeEach((to, from, next) => {
  // 首先通过页面链接上的项目Id，获取其对应的appid
  getAppid(to).then(() => {
    // 如果是本地开发环境，模拟获取到openid
    if (process.env.NODE_ENV === 'development') {
      sessionStorage.setItem('openid', 'o75jG6XqyF1CVJQs55Focu6QaTxA') // ZMH 测试号-李
    }
    document.title = ''
    // 当前路径上的openid 和 isRedrect
    checkRouteQuery(to)
    // 如果是非微信环境， 直接获取全局参数并进入页面
    let vue = new Vue()
    if (!vue.checkIfWxClient()) {
      getGlobalData(next)
    // 如果是微信环境，该页面设置了无需授权，直接获取全局参数并进入页面
    } else if (to.meta.unAuthorization) {
      getGlobalData(next)
    // 如果是微信环境，且页面需要授权
    } else {
      // 首先获取openid
      checkOpenid().then(() => {
        // 获取全局参数并进入页面
        getGlobalData(next)
      })
    }
  }).catch(e => {
    Toast({
      message: e.message
    })
  })
})

route.afterEach((to, from) => {
  setTimeout(() => {
    let vue = new Vue()
    // 如果该页面不需要单独设置 微信工具菜单显隐 和 设置分享
    if (!to.meta.setMenuAndShareInPage) {
      let param = {}
      // 是否显示所有微信工具菜单
      if (to.meta.showAllMenu) {
        param.showAllMenu = to.meta.showAllMenu
      }
      // 显示微信工具菜单列表
      if (to.meta.showMenuList) {
        param.showMenuList = to.meta.showMenuList
      }
      // 是否禁止自定义分享
      if (to.meta.forbitShare) {
        param.forbitShare = to.meta.forbitShare
      }
      // 分享配置参数
      if (to.meta.shareInfo) {
        param.shareInfo = to.meta.shareInfo
      }
      vue.setWxToolMenuAndShare(param)
    }
    // // 如果不是详请页面，则触发访问数据埋点
    // if (to.name !== 'articleDetail' &&
    //     to.name !== 'publicClassDetail' &&
    //     to.name !== 'liveDetail') {
    //   // 访问数据埋点
    //   setTimeout(() => {
    //     // 如果页面有pageId
    //     if ((to.query.pageId || to.params.pageId) && !to.meta.isTrack) {
    //       actionTrack({
    //         action: 0,
    //         mode: 'page',
    //         page: to.meta.title || '',
    //         pageId: to.query.pageId || to.params.pageId
    //       })
    //     }
    //   }, 700)
    // }
  }, 300)
  Toast.clear()
  Dialog.close()
})
export default route
